package com.gm.server.voice.utils;



import javax.sound.sampled.*;
import java.io.*;
import java.net.*;

public class VoiceClient {
    private static final String SERVER_IP = "192.168.2.100"; // 替换为服务器IP
    private static final int PORT = 11822;

    public static void main(String[] args) {
        try {
            Socket socket = new Socket(SERVER_IP, PORT);
            System.out.println("已连接到服务器: " + SERVER_IP);

            // 启动接收线程（接收服务器音频并播放）
            new Thread(new ReceiveAudio(socket)).start();
            // 启动发送线程（采集本地音频并发送）
            new Thread(new SendAudio(socket)).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 接收音频并播放（与服务器相同）
    static class ReceiveAudio implements Runnable {
        private final Socket socket;

        public ReceiveAudio(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                SourceDataLine speaker = AudioUtils.getSpeaker();
                speaker.start();

                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = in.read(buffer)) != -1) {
                    speaker.write(buffer, 0, bytesRead);
                }

                speaker.drain();
                speaker.close();
            } catch (IOException | LineUnavailableException e) {
                e.printStackTrace();
            }
        }
    }

    // 采集音频并发送（与服务器相同）
    static class SendAudio implements Runnable {
        private final Socket socket;

        public SendAudio(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                OutputStream out = socket.getOutputStream();
                TargetDataLine microphone = AudioUtils.getMicrophone();
                microphone.start();

                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = microphone.read(buffer, 0, buffer.length)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }

                microphone.close();
            } catch (IOException | LineUnavailableException e) {
                e.printStackTrace();
            }
        }
    }
}